package com.example.blog.controller;

import com.example.blog.Utils.JWTUtils;
import com.example.blog.Utils.SecurityUtil;
import com.example.blog.advice.PasswordIncorrectException;
import com.example.blog.advice.UserNotFoundException;
import com.example.blog.constant.Contants;
import com.example.blog.exception.BlogException;
import com.example.blog.model.UserInfo;
import com.example.blog.result.Result;
import com.example.blog.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("/login")
    public Result login(String userName, String password) throws UserNotFoundException, PasswordIncorrectException {
        log.info("用户登录，username：{}",userName);
        UserInfo userInfo = userService.getUserInfoByName(userName);
        if (userInfo == null) {
            throw new UserNotFoundException("用户不存在");
        }
        //密码错误的情况
        if (!SecurityUtil.verify(password, userInfo.getPassword())){
            log.error("密码错误");
            return Result.fail("密码错误");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("id",userInfo.getId());
        map.put("username",userInfo.getUserName());
        String jwt = JWTUtils.genJwt(map);
        return  Result.success(jwt);
    }
    //获取当前用户的信息
    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        log.info("获取用户信息");
        String token = request.getHeader(Contants.TOKEN_HEADER_CONSTANT);
        Integer id = JWTUtils.getUserIdBytoken(token);
        if (id == null) {
            return null;
        }
        UserInfo userInfo = userService.getUserInfoById(id);
        return Result.success(userInfo);
    }
    //根据博客id获取作者信息
    @RequestMapping("/getAuthorInfo")
    public Result getAuthorInfo(@NonNull Integer blogId) {
        log.info("获取博客信息");
        UserInfo userInfo = userService.getAuthorById(blogId);
        return Result.success(userInfo);
    }
}
